package com.geek.novel.dialog

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.base.BaseActivity
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookRead
import com.geek.novel.listener.MenuItemInflaterViewListener
import com.geek.novel.services.ImportBookService
import com.geek.novel.services.impl.ImportBookServiceImpl
import com.geek.novel.utils.FileUtil
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import com.mingyuers.permission.PermissionAnywhere
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.io.File

/**
 * 主页的菜单弹框
 */
class MainMenuDialog(val mContext: BaseActivity) : MenuListDialog(mContext, R.layout.listview_menu_item, ArrayList()) {

    /**导入本地书籍*/
    private val keyMenuitemImportBook = "importBook"

    /**重写绑定事件的方法，处理本地数据*/
    override fun bindEvent(dialogView: View) {
        list.add(MenuItem(keyMenuitemImportBook, "导入本地书籍"))
        this.onItemClickListener = MenuItemClickListener()
        this.inflaterViewListener = MenuItemInflaterViewListener()

        super.bindEvent(dialogView)
    }

    /**菜单按钮点击的监听器*/
    inner class MenuItemClickListener: MenuListDialog.MenuItemClickListener{
        override fun onItemClick(item: MenuItem, view: View, position: Int): Boolean {
            when(item.key){
                //导入本地书籍
                keyMenuitemImportBook->{
                    PermissionAnywhere.requestPermission(
                        arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
                    ) { _, _, _ ->
                        val intent = Intent(Intent.ACTION_GET_CONTENT)
                        intent.type = "text/plain" //txt文件类型限制
                        intent.addCategory(Intent.CATEGORY_OPENABLE)
                        mContext.startActivityForResult(intent, Constant.ACTIVITY_RESULT_READ_FILE_SUCCESS)
                    }
                }
            }
            return true
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        //导入本地书籍的处理逻辑
        if(requestCode == Constant.ACTIVITY_RESULT_READ_FILE_SUCCESS) {
            if(data == null){
                ToastUtils.toast("取消导入书籍")
                return
            }

            val uri: Uri = data.data!!
            LogCatUtil.i(this.javaClass.name, "获取到的结果：${uri}")

            val filePath = FileUtil.getPath(context, uri)
            if(filePath == null){
                ToastUtils.toast("获取文件失败，请检查文件格式是否正确")
                return
            }
            val importBookService: ImportBookService = ImportBookServiceImpl()
            importBookService.importBook(File(filePath))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(object: Observer<Any?> {
                    override fun onNext(t: Any) {
                        t as BookRead
                        LogCatUtil.i(this.javaClass.name, "书籍保存完毕：${t.bookName}")
                        //发送事件, 刷新列表
                        mContext.sendHandlerMessage(Constant.handler_event_my_book_update_list)
                    }
                    override fun onSubscribe(d: Disposable) {
                    }
                    override fun onError(e: Throwable) {
                        ToastUtils.toast(e.message)
                    }
                    override fun onComplete() {
                    }
                })
        }
    }

}